package com.sh.shanhuo.database.sort;

import android.content.Context;

import com.sh.shanhuo.database.web.WebInfoEntity;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

@Database(entities = {SortInfoEntity.class}, version = 1,exportSchema = false)
public abstract class SortInfoDatabase extends RoomDatabase {

    private static volatile SortInfoDatabase instance;
    private static SupportSQLiteDatabase database;

    public static SortInfoDatabase getDatabase(Context context) {
        if (instance == null) {
            synchronized (SortInfoDatabase.class) {
                if (instance == null) {
                    instance = Room.databaseBuilder(context.getApplicationContext(),
                            SortInfoDatabase.class, "sort_info_database")
                            .addCallback(new Callback() {
                                //第一次创建数据库时调用，但是在创建所有表之后调用的
                                @Override
                                public void onCreate(@NonNull SupportSQLiteDatabase db) {
                                    database = db;
                                    super.onCreate(db);
                                }

                                //当数据库被打开时调用
                                @Override
                                public void onOpen(@NonNull SupportSQLiteDatabase db) {
                                    database = db;
                                    super.onOpen(db);
                                }
                            })
                            .fallbackToDestructiveMigration() // 数据库版本升级，数据迁移(本项目删除并重新创建整个数据库，因为每次在首页获取设备信息，直接保存)
                            .allowMainThreadQueries()//允许在主线程查询数据
                            .build();
                }
            }
        }
        return instance;
    }

    public static void onDestroy() {
        instance = null;
    }

    public static SupportSQLiteDatabase getDatabase() {
        return database;
    }

    public abstract SortInfoDao getSortInfoDao();

}
